package com.ssm.subject.infra.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密util
 */
public class DruidEncryptUtil {

    private static String publicKey; //公钥

    private static String privateKey; //私钥

    static { //随着类的创建而执行，且只执行一次
        try {
            String[] genKeyPair = ConfigTools.genKeyPair(512); //生成一个512位的加密对
            privateKey = genKeyPair[0];
            System.out.println("私钥为=" + privateKey);
            publicKey = genKeyPair[1];
            System.out.println("公钥为=" + publicKey);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);

        }
    }
    public static String encrypt(String plainText) throws Exception {
        String s = ConfigTools.encrypt(privateKey, plainText); //使用私钥加密
        System.out.println("加密后:" + s);
        return s;
    }

    public static String decrypt(String plainText) throws Exception {
        String s = ConfigTools.decrypt(publicKey, plainText); //使用公钥解密
        System.out.println("解密后:" + s);
        return s;
    }

    public static void main(String[] args) throws Exception {
        String encrypted = encrypt("ssm030927");
        decrypt(encrypted);
    }
}
